package test12;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Demo {
    public static void main(String[] args) throws IOException {
        //创建服务器端
        ServerSocket serverSocket=new ServerSocket(7000);
        //创建线程池
        ExecutorService pool= Executors.newFixedThreadPool(10);

        while (true){
            //侦听客户端
            Socket socket=serverSocket.accept();

            //使用线程池执行方法
            pool.submit(()->{
                BufferedReader br=null;
                FileInputStream fis=null;
                OutputStream os=null;
                try {
                    //获取请求行信息
                    br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    String url=br.readLine();
                    String fileName=url.split(" ")[1].substring(1);

                    //读取请求的文件,并发送
                    fis=new FileInputStream(new File("src\\html\\"+fileName));
                    os=socket.getOutputStream();
                    os.write("HTTP/1.1 200 ok\r\n".getBytes());
                    os.write("Content-Type:text/html;charset=utf-8\r\n".getBytes());
                    os.write("\r\n".getBytes());

                    int len;
                    byte[] buff=new byte[1024];
                    while ((len=fis.read(buff))!=-1){
                        os.write(buff,0,len);
                    }
                    //设置结束标记
                    socket.shutdownOutput();

                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    if(br!=null){
                        try {
                            br.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if(fis!=null){
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if(os!=null){
                        try {
                            os.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

            });
        }
    }
}
